#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
import argparse

def to_ns(s):
    pat = re.compile(r'(ns|us|ms|s)$');

    arr = pat.split(s)
    t = float(arr[0])

    if (arr[1] == "ms"):
        t = t * 1000 * 1000
    elif (arr[1] == "s"):
        t = t * 1000 * 1000*1000
    elif (arr[1] == "us"):
        t = t * 1000;
    elif (arr[1] == "ns"):
        t = t / 1000.0
    else:
        t = 0
        print ("Invalid time: %s" % s)

    #print("c:%f" %t)
    #print()
    return t 

def csv_file_add_line_num(inf_name,outf_name):
    inf = open(inf_name,'r')
    outf = open(outf_name, 'w')
    first_line = inf.readline()
    first_line = first_line.strip()+",line_num\n"
    outf.write(first_line)
    print("first_line:%s"%first_line)
    line_num = 0
    for line in inf.readlines():
        outf.write(line.strip()+","+str(line_num)+"\n")
        line_num += 1
    inf.close()
    outf.close()


def parse_csv_file(inf_name, outf_name, args):
    bit_count = 0
    in_dat = 0
    out_dat = 0

    prev_t = curr_t = 0

    inf = open(inf_name, 'r')
    outf = open(outf_name, 'w')

    fields = inf.readline().strip().lower().split(',')

    try:
        idx_bus = fields.index(args.bus.lower())
    except ValueError:
        sys.stderr.write("incorrect sck/mosi/miso column specified.\n")
        return

    data_idx = 0
    curr_bus = 1
    hi_begin_time = 0
    lo_begin_time = 0
    print_idx = 0
    time_interval = 0
    Record = []
    RecordList = []
    for line in inf.readlines():
        values = line.split(',')

        curr_t = to_ns(values[0])

        prev_bus = curr_bus
        curr_bus = int(values[idx_bus])

        if curr_bus == 1 and prev_bus == 0:
           hi_begin_time = curr_t

        if curr_bus == 0 and  prev_bus == 1:
            lo_begin_time = curr_t

        if hi_begin_time > 0 and curr_bus == 0 and prev_bus == 1:
            Record=[1,curr_t - hi_begin_time]
            RecordList.append(Record)
            #print ("    H,%dns,    " %(curr_t - hi_begin_time),)
            print_idx = print_idx + 1
        
        if lo_begin_time > 0 and curr_bus == 1 and prev_bus == 0:
            #print ("    L,%dns,    " %(curr_t - lo_begin_time),)
            Record=[0,curr_t - lo_begin_time]
            RecordList.append(Record)
            print_idx = print_idx + 1
            
        #if print_idx >= 10:
            #print()
            #print_idx = 0
    inf.close()
    outf.close()
    return RecordList

def filter_signal(RecordList):
    i = 1
    prev_record = []
    record = []
    #print("len:%d" %len(RecordList))
    if  len(RecordList) < 1:
        return

    #filter useless low signal
    while  i < len(RecordList):
        record = RecordList[i]
        if  record[0] == 0 and record[1] < 2000:
            RecordList[i-1][1] += record[1]
            del RecordList[i]
        else:
            i += 1

    
    i = 1 
    while  i < len(RecordList):
        record = RecordList[i]
        prev_record = RecordList[i-1]
        if  record[0] == 1 and prev_record[0] == 1:
            RecordList[i-1][1] += record[1]
            del RecordList[i]
        else:
            i += 1

def print_out_hi(RecordList):
    i = 0
    while i < len(RecordList):
        if RecordList[i][0] == 1:
            print("%dns" %RecordList[i][1])
        i += 1

def print_out_cycle(RecordList):
    i = 0
    num = 0
    while i < len(RecordList):
        if RecordList[i][0] == 0:
            if  i >= 1:
                num += 1
                print("%d,cycle:%dns" %(num,RecordList[i][1] + RecordList[i-1][1]))
        i += 1

def main():
    parser = argparse.ArgumentParser(description = "decoder for ZLG csv")

    parser.add_argument('--bus', type=str, default='signal')
    parser.add_argument('--print_type', type=str, default='high_level')
    
    parser.add_argument('csv_files', nargs='+')

    args = parser.parse_args()
    RecordList = []

    for inf_name in args.csv_files:
        if inf_name.lower().find('.csv') < 0:
            outf_name = inf_name + '.st'
        else:
            outf_name = inf_name.replace('.csv', '.st')

        RecordList = parse_csv_file(inf_name, outf_name, args)
        filter_signal(RecordList)
        if args.print_type == 'high_level':
            print_out_hi(RecordList)
        else:
            print_out_cycle(RecordList)

if __name__ == "__main__":
    main()
